<?php

namespace application\middleware;

use fastphp\Middleware;
use fastphp\Request;
use fastphp\Response;
use fastphp\Session;

/**
 * 认证中间件
 * 验证用户是否已登录
 */
class Auth implements Middleware
{
    /**
     * @inheritDoc
     */
    public function handle(Request $request, Response $response, callable $next)
    {
        // 获取Session实例
        $session = Session::getInstance();
        
        // 检查用户是否已登录
        if (!$session->has('user')) {
            // 用户未登录，重定向到登录页面或返回错误
            $response->status(401);
            $response->json([
                'code' => 401,
                'message' => '未授权访问'
            ]);
            return $response;
        }
        
        // 用户已登录，继续处理请求
        return $next($request, $response);
    }
}